const net = require('net');
const { dot, contral } = require('./lib/parse');
const dotMochaData = require('./mocha/dot')
const fs = require('fs');
const promisify = require('util').promisify;
const fsp = fspromisify(['open', 'read', 'close', 'fstat', 'writeFile']);

const OFFSET = 1024;
const PART_SIZE = 10264;
const filePath = './mocha/test2.dat'

function fspromisify(methods) {
    let fsp = {};
    methods.forEach(m => fsp[m] = promisify(fs[m]));
    return fsp;
}


function createServer(isRight) {
    let log = process.env.NODE_ENV === 'test' ? noop :
        console.log.bind(console, `[${isRight?'Right':'Left'}]`);

    // tcp服务端
    const server = net.createServer(function(socket) {
        log('client connect');
        let t = null;
        let isStart = false;
        let commandObj;

        socket.on('data', async function(data) {
            commandObj = contral.parse(data);
            isStart = commandObj.status
            log('recive data', commandObj)

            let mochaCount = await getMochaCount();
            console.log('mochaCount', mochaCount)
            let per = 5;
            let rts = 31;

            // wait(2000).then(() => {
            //     isStart = false
            //     return wait(2000)
            // }).then(() => {
            //     isStart = true
            // })

            function writeMochaData(i, max, n = 0, isFistRt = true) {
                if (i < max) {
                    if (isStart) {
                        t && clearTimeout(t);
                        t = setTimeout(async () => {
                            let buffer = await mochaData(i);
                            let obj = dot.parse(buffer);

                            // 修改左右顺序
                            if (isRight !== obj.isRight) {
                                return writeMochaData(i + 1, max, n, isFistRt);
                            }

                            // 回拉
                            // if (isFistRt && i > rts) {
                            //     if (n >= rts) {
                            //         isFistRt = false
                            //     } else {
                            //         n = n + 2
                            //     }
                            // }

                            obj.curDistance = isRight ? i * per / 2 : (i - 1) * per / 2;
                            obj.curDistance = obj.curDistance - n * per;
                            obj.curDistance = obj.curDistance > 5 ? obj.curDistance : 5
                            if (commandObj.mileageDir) {
                                obj.curDistance = commandObj.distance + obj.curDistance
                            } else {
                                obj.curDistance = commandObj.distance - obj.curDistance
                            }


                            let newBuffer = dot.gen(obj)
                            log('send data[' + i + ']', obj.curDistance, obj.isRight)

                            socket.write(newBuffer);
                            i = i + 2;

                            writeMochaData(i, max, n, isFistRt);
                        }, 300)
                    } else {
                        wait(1000).then(() => {
                            writeMochaData(i, max, n, isFistRt);
                        })
                    }

                } else {
                    log('file empty, repeat send');
                    let i = isRight ? 0 : 1;
                    writeMochaData(i, mochaCount);
                }
            }

            let i = isRight ? 0 : 1;
            writeMochaData(i, mochaCount);

        });

        socket.on('close', function() {
            log('client close');
            t && clearTimeout(t);
        });

        socket.on('error', (error) => {
            log(error);
            t && clearTimeout(t);
        })

    });

    return server;
}

/**
 * 随机整型
 * @param  {[type]} min [description]
 * @param  {[type]} max [description]
 * @return {[type]}     [description]
 */
function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

// function mochaData(curDistance, isRight) {
//     dotMochaData.curDistance = curDistance;
//     dotMochaData.isRight = isRight;
//     return dot.gen(dotMochaData);
// }

async function mochaData(i) {
    let { size } = await fs.lstatSync(filePath);

    if ((size - OFFSET) / PART_SIZE > i) {
        let buffer = Buffer.alloc(PART_SIZE);

        let fd = await fsp.open(filePath, 'r');
        let start = OFFSET + i * PART_SIZE;
        await fsp.read(fd, buffer, 0, PART_SIZE, start);
        await fsp.close(fd)
        return buffer;
    }

    return Buffer.alloc(0)
}

async function getMochaCount() {
    let { size } = await fs.lstatSync(filePath);
    return (size - OFFSET) / PART_SIZE
}

async function wait(dely) {
    return new Promise((reslove) => {
        setTimeout(() => {
            reslove()
        }, dely)
    })
}

function noop() {}

module.exports = createServer;